<template>
  <div id="cont">
    <div class="ava">
      <img :src="uinfo.avatars" :key="k" />
      <form enctype="multipart/form-data" method="post">
        <input type="file" name="avatars" class="update opacity" @change="updateAva" />
        <button class="update">更新</button>
      </form>
    </div>
    <div class="inf">
      <p>{{ uinfo.username }}</p>
    </div>
  </div>
</template>

<script>
import app from '@/utils/index';
import { mapActions } from 'vuex';

export default {
  name: 'ucenter',
  data() {
    return {
      uinfo: {},
      k: 0
    }
  },
  created() {
    this.uinfo = this.$store.state.uinfo;
  },
  methods: {
    ...mapActions([
			'SET_UINFO'
		]),
    updateAva(e) {
      const files = e.target.files || e.dataTransfer.files;
			let formdata = new FormData();
			if(!files.length) {
				return false;
			}
			formdata.append("avatars", files[0]);
			app.request({
				url: '/api/updateAvatars',
				method: 'POST',
				headers: {'Content-Type': 'application/x-www-form-urlencoded'},
				data: formdata,
				success: response => {
					const res = response.data;
					if(res.s) {
            this.uinfo.avatars = res.d.avatars;
            if(this.k == 1) {  // 特殊处理（由于头像的名称相同，导致数据不会重新渲染），通过k值来告诉vue组件的变化
              this.k = 0;
            }else {
              this.k = 1;
            }
            this.$store.dispatch('SET_UINFO', res.d);
					}
				}
			})
    }
  }
}
</script>

<style lang="less" scoped>
  .ava {
    position: relative;
    width: 120px;
    height: 120px;
    border: 3px solid #fff;
    outline: 1px solid #ddd;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
      vertical-align: middle;
    }
    .update {
      position: absolute;
      right: 0;
      bottom: 0;
      // display: none;
      width: 40px;
      height: 25px;
      border: 0;
      border-radius: 3px 0 0 0;
      background-color: rgba(255,255,255, 0.8);
      font-size: 12px;
      line-height: 25px;
      outline: none;
      z-index: 111;
      cursor: pointer;
    }
    &:hover {
      .update {
        display: block;
      }
      
    }
    .opacity {
      opacity: 0;
      cursor: pointer;
      z-index: 112;
    }
  }
</style>